<?php
/**
 * Created by PhpStorm.
 * User: rocky
 * Date: 2022-03-10
 * Time: 22:25
 */

namespace plugin\thinkphp\common;

use ExAdmin\ui\component\Component;
use ExAdmin\ui\contract\LoginAbstract;
use ExAdmin\ui\response\Message;
use ExAdmin\ui\response\Response;
use ExAdmin\ui\support\Container;
use ExAdmin\ui\support\Token;
use think\facade\Cache;
use think\facade\Validate;


class Login extends LoginAbstract
{

    /**
     * 登陆页
     * @return Component
     */
    public function index(): Component
    {
        return admin_view(plugin()->thinkphp->getPath(). '/views/login.vue')->attrs([
            'webLogo' => admin_sysconf('web_logo'),
            'webName' => admin_sysconf('web_name'),
            'webMiitbeian' => admin_sysconf('web_miitbeian'),
            'webCopyright' => admin_sysconf('web_copyright'),
            'deBug' => env('APP_DEBUG'),
        ]);
    }

    /**
     * 登录验证
     * @param array $data 提交数据
     * @return Message
     */
    public function check(array $data): Message
    {
        $validate = Validate::rule([
            'username' => 'require',
            'password' => 'require|min:5'
        ])->message([
            'username.require' => admin_trans('login.account_not_empty'),
            'password.require' => admin_trans('login.password_not_empty'),
            'password.min' => admin_trans('login.password_min_length'),
        ]);
        $validate->check($data);
        if ($validate->getError()) {
            return message_error($validate->getError());
        }
        $cacheKey = request()->ip().date('Y-m-d');
        $errorNum = Cache::get($cacheKey);
        if($errorNum > 3 && !Container::getInstance()->captcha->check($data['verify'],$data['hash'])){
            return message_error(admin_trans('login.captcha_error'));
        }
        $model = plugin()->thinkphp->config('database.user_model');
        $user = $model::where('username', $data['username'])->find();
        if (!$user || !password_verify($data['password'], $user->password)) {
            Cache::inc($cacheKey);
            return message_error(admin_trans('login.error'));
        }

        return message_success(admin_trans('login.success'))->data([
            'token' => Token::encode($user->toArray()),
        ]);
    }
    /**
     * 获取验证码
     * @return Response
     */
    public function captcha(): Response
    {
        $cacheKey = request()->ip() . date('Y-m-d');
        $errorNum = Cache::get($cacheKey);
        $captcha = Container::getInstance()->captcha->create();
        $captcha['verification'] = $errorNum > 3;
        return Response::success($captcha);
    }
    /**
     * 退出登录
     * @return Message
     */
    public function logout(): Message
    {
        Token::logout();
        return message_success(admin_trans('login.logout'));
    }
}
